package com.zys.http.processor.spring;

import cn.hutool.core.text.CharSequenceUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.zys.http.constant.HttpEnum;
import com.zys.http.entity.param.ParamProperty;
import com.zys.http.entity.tree.MethodNodeData;
import com.zys.http.extension.setting.HttpSetting;
import com.zys.http.processor.AbstractJavaProcessor;
import com.zys.http.tool.UrlTool;
import com.zys.http.ui.tree.node.MethodNode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * @author zys
 * @since 2025-01-13
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SpringJavaProcessor extends AbstractJavaProcessor {
    public static final SpringJavaProcessor INSTANCE = new SpringJavaProcessor();

    @Override
    public boolean isTargetController(PsiElement element) {
        if (!(element instanceof PsiClass psiClass)) {
            return false;
        }
        String customAnno = HttpSetting.getInstance().getCustomAnno();

        return Arrays.stream(psiClass.getAnnotations()).anyMatch(annotation ->
                isTargetAnnotation(annotation, SpringEnums.Controller.CONTROLLER.getClazz()) ||
                        isTargetAnnotation(annotation, SpringEnums.Controller.REST_CONTROLLER.getClazz()) ||
                        (CharSequenceUtil.isNotBlank(customAnno) && isTargetAnnotation(annotation, customAnno))
        );
    }

    @Override
    @SneakyThrows
    @SuppressWarnings("deprecation")
    public List<? extends PsiElement> moduleControllers(Module module, Project project) {
        Optional<GlobalSearchScope> scopeOp = Optional.of(module).map(Module::getModuleScope);
        Collection<PsiAnnotation> annotations = ApplicationManager.getApplication().runReadAction((Computable<Collection<PsiAnnotation>>) () -> {
            Collection<PsiAnnotation> all = new ArrayList<>();
            for (SpringEnums.Controller controller : SpringEnums.Controller.values()) {
                if (controller.equals(SpringEnums.Controller.RESPONSE_BODY)) {
                    continue;
                }
                String shortClassName = controller.getShortClassName();
                all.addAll(scopeOp.map(ms -> JavaAnnotationIndex.getInstance().get(shortClassName, project, ms)).orElse(new ArrayList<>()));
            }

            String customAnno = HttpSetting.getInstance().getCustomAnno();
            if (CharSequenceUtil.isNotEmpty(customAnno) && !customAnno.endsWith(".")) {
                String shortName = customAnno.substring(customAnno.lastIndexOf('.') + 1);
                all.addAll(scopeOp.map(ms -> JavaAnnotationIndex.getInstance().get(shortName, project, ms)).orElse(new ArrayList<>()));
            }
            return all;
        });

        return annotations.stream()
                .map(PsiElement::getParent)
                .map(PsiModifierList.class::cast)
                .map(PsiModifierList::getParent)
                .filter(PsiClass.class::isInstance)
                .map(PsiClass.class::cast)
                .toList();
    }


    @Override
    public List<String> controllerPaths(PsiElement element) {
        if (!(element instanceof PsiClass psiClass)) {
            return DEFAULT_ANNO_VALUE;
        }

        PsiModifierList modifierList = psiClass.getModifierList();
        if (Objects.isNull(modifierList)) {
            return DEFAULT_ANNO_VALUE;
        }
        Set<? extends PsiElement> annotations = this.controllerAnnotations(element);
        for (PsiElement annotation : annotations) {
            if (isTargetAnnotation(annotation, SpringEnums.Method.REQUEST.getClazz())) {
                return annotationValues(annotation, new String[]{VALUE_KEY, "path"});
            }
        }

        return DEFAULT_ANNO_VALUE;
    }

    @Override
    public boolean isTargetMethod(PsiElement element) {
        if (!(element instanceof PsiMethod method)) {
            return false;
        }
        PsiAnnotation[] annotations = method.getAnnotations();
        for (PsiAnnotation annotation : annotations) {
            if (SpringEnums.Method.contains(annotation)) {
                return true;
            }
        }
        PsiMethod[] superMethods = PsiSuperMethodImplUtil.findSuperMethods(method);
        for (PsiMethod superMethod : superMethods) {
            if (isTargetMethod(superMethod)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<String> methodPaths(PsiElement element) {
        if (!(element instanceof PsiMethod method)) {
            return DEFAULT_ANNO_VALUE;
        }
        PsiAnnotation[] annotations = method.getAnnotations();

        for (PsiAnnotation annotation : annotations) {
            if (SpringEnums.Method.contains(annotation)) {
                return annotationValues(annotation, new String[]{VALUE_KEY, "path"});
            }
        }

        PsiMethod[] superMethods = PsiSuperMethodImplUtil.findSuperMethods(method);
        for (PsiMethod superMethod : superMethods) {
            return methodPaths(superMethod);
        }
        return DEFAULT_ANNO_VALUE;
    }

    @Override
    public List<MethodNode> methodNodeCreate(PsiElement element, String controllerPath, String contextPath, boolean isFirstCall) {
        if (!(element instanceof PsiMethod method)) {
            return Collections.emptyList();
        }
        PsiAnnotation[] annotations = method.getAnnotations();

        List<MethodNode> res = new ArrayList<>();
        for (PsiAnnotation annotation : annotations) {
            if (!SpringEnums.Method.contains(annotation)) {
                continue;
            }

            HttpEnum.HttpMethod httpMethod = SpringEnums.Method.get(annotation);

            List<String> names = annotationValues(annotation, new String[]{VALUE_KEY, "path"});
            for (String name : names) {
                MethodNodeData data = new MethodNodeData(httpMethod, name, controllerPath, contextPath);
                data.setDescription(methodSwagger(method));
                data.setPsiElement(method);
                res.add(new MethodNode(data));
            }
        }
        // 获取父级接口
        if (isFirstCall && res.isEmpty()) {
            PsiMethod[] superMethods = PsiSuperMethodImplUtil.findSuperMethods(method);
            for (PsiMethod superMethod : superMethods) {
                List<MethodNode> list = methodNodeCreate(superMethod, controllerPath, contextPath, false).stream()
                        .peek(o -> o.getValue().setPsiElement(method)).toList();
                res.addAll(list);
            }
        }

        return res;
    }


    @Override
    public void parameterParse(@NotNull PsiElement element, @NotNull Map<String, ParamProperty> map, boolean isJsonPretty) {
        if (!(element instanceof PsiParameter parameter)) {
            return;
        }
        String parameterName = parameter.getName();
        PsiType parameterType = parameter.getType();

        String[] keys = new String[]{VALUE_KEY, NAME_KEY};
        if (parameter.hasAnnotation(SpringEnums.Param.REQUEST_HEADER.getClazz())) {
            parameterName = annotationValue(parameter.getAnnotation(SpringEnums.Param.REQUEST_HEADER.getClazz()), keys);
            // 如果参数注解带 @RequestHeader, 默认 String, 不作特殊处理
            ParamProperty property = map.getOrDefault(REQUEST_TYPE_KEY, null);
            if (property == null) {
                map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            }
            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.HEADER));
            return;
        }
        HttpEnum.ParamUsage paramUsage = HttpEnum.ParamUsage.URL;
        PsiAnnotation requestParamAnno = parameter.getAnnotation(com.zys.http.processor.spring.SpringEnums.Param.REQUEST_PARAM.getClazz());

        if (Objects.nonNull(requestParamAnno)) {
            // @RequestParam 是否有 value 或 name 属性, 如果有会将请求参数名变为那个
            String annotationValue = annotationValue(requestParamAnno, keys);
            if (CharSequenceUtil.isNotEmpty(annotationValue)) {
                parameterName = annotationValue;
            }
        }

        String canonicalText = parameterType.getCanonicalText();
        if (canonicalText.contains("org.springframework.web.multipart.MultipartFile")) {
            // 说明是文件
            PsiAnnotation requestPartAnno = parameter.getAnnotation(com.zys.http.processor.spring.SpringEnums.Param.REQUEST_PART.getClazz());
            if (Objects.nonNull(requestPartAnno)) {
                // @RequestPart 是否有 value 或 name 属性, 如果有会将请求参数名变为那个
                String annotationValue = annotationValue(requestPartAnno, keys);
                if (CharSequenceUtil.isNotEmpty(annotationValue)) {
                    parameterName = annotationValue;
                }
            }

            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.FILE));
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.MULTIPART_FORM_DATA, HttpEnum.ParamUsage.HEADER));
            return;
        }

        PsiAnnotation pathVariableAnno = parameter.getAnnotation(com.zys.http.processor.spring.SpringEnums.Param.PATH_VARIABLE.getClazz());
        if (Objects.nonNull(pathVariableAnno)) {
            // @PathVariable 是否有 value 或 name 属性, 如果有会将请求参数名变为那个
            String annotationValue = annotationValue(pathVariableAnno, keys);
            paramUsage = HttpEnum.ParamUsage.PATH;
            if (CharSequenceUtil.isNotEmpty(annotationValue)) {
                parameterName = annotationValue;
            }
        }

        Object paramDefaultTypeValue = typeDefaultValue(parameterType, parameter.getProject());
        if (Objects.isNull(paramDefaultTypeValue)) {
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            return;
        }

        boolean isJson = parameter.hasAnnotation(com.zys.http.processor.spring.SpringEnums.Param.REQUEST_BODY.getClazz());
        typeParseResult(parameterName, paramDefaultTypeValue, isJson, isJsonPretty, map, paramUsage);
    }

    @Override
    public List<PostmanItem> postmanMethodItems(PsiElement element, String modulePath, String controllerPath) {
        if (!isTargetMethod(element)) {
            return Collections.emptyList();
        }
        PsiMethod method = (PsiMethod) element;

        String methodSwagger = methodSwagger(method);
        methodSwagger = CharSequenceUtil.isEmpty(methodSwagger) ? method.getName() : methodSwagger;

        for (PsiAnnotation annotation : method.getAnnotations()) {
            HttpEnum.HttpMethod httpMethod = SpringEnums.Method.get(annotation);
            if (httpMethod == null) {
                continue;
            }
            List<PostmanItem> res = new ArrayList<>();
            List<String> methodPaths = methodPaths(element);
            for (String path : methodPaths) {
                PostmanItem item = postmanItemCreate(methodSwagger, httpMethod.name(), UrlTool.buildMethodUri(modulePath, controllerPath, path));
                this.postmanItemPropertyCompletion(method, item);
                res.add(item);
            }
            return res;
        }
        return Collections.emptyList();
    }


}
